﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using CSVExportImport.Exceptions;

namespace CSVExportImport
{

    public class ReaderWrapper
    {
        TextReader reader;
        
        public ReaderWrapper(TextReader reader)
        {
            this.reader = reader;
        }

        bool newLineReaded = false;
        bool end = false;
        public bool NewLineReaded()
        {
            return newLineReaded;
        }

        protected String Read()
        {
            bool qreaded = false;
            bool escapeNext = false;

            String readed = String.Empty;

            newLineReaded = false;
            if (end)
            {
                return null;
            }
            while (true)
            {
                char[] i = new char[1];
                if (reader.Read(i, 0, 1) != 1)
                {
                    end = true;
                    return readed;
                }
                readed = readed + i[0];

                if (readed.EndsWith(Parameters.QUOTE_ESCAPE) && qreaded)
                {
                    escapeNext = true;
                }
                else if (readed.EndsWith(Parameters.QUOTE))
                {
                    if (escapeNext)
                    {
                        escapeNext = false;
                    }
                    else if (qreaded)
                    {
                        qreaded = false;
                    }
                    else
                    {
                        qreaded = true;
                    }
                }
                else if (readed.EndsWith(Parameters.ITEM_SEPARATOR) && !qreaded)
                {
                    return readed.Remove(readed.Length - Parameters.ITEM_SEPARATOR.Length); ;
                }
                else if (readed.EndsWith(Parameters.LINE_SEPARATOR) && !qreaded)
                {
                    newLineReaded = true;
                    return readed.Remove(readed.Length - Parameters.LINE_SEPARATOR.Length); ;
                }
            }
        }
        public String ReadValue()
        {
            return Parameters.ParseValue(this.Read());
        }

        public void AssertNewLine()
        {
            if (!NewLineReaded())
            {
                throw new CSVExportImportException("New line expected", CSVExportImportException.ExceptionType.NewLineExpected, 0);
            }
        }
        public void AssertNotNewLine()
        {
            if (NewLineReaded())
            {
                throw new CSVExportImportException("New line not expected", CSVExportImportException.ExceptionType.NewLineNotExpected, 0);
            }
        }
        public bool EnfOfStreamReached
        {
            get { return end; }
        }
    }
}
